import json
# 1.
def format_date(day_of_week, date_of_month, month, year):
    days_of_week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
    months_of_year = [
        "January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"
    ]

    formatted_day_of_week = days_of_week[int(day_of_week) - 1]
    formatted_month = months_of_year[int(month) - 1]

    return f"{formatted_day_of_week}, {int(date_of_month)} {formatted_month} {year}"

# 2.
with open('US_births_2000-2014.json', 'r') as file:
    births = json.load(file)
    # 3.
    births_abbreviated = {}
    for birth in births:
        formatted_date = format_date(birth['day_of_week'], birth['date_of_month'], birth['month'], birth['year'])
        births_abbreviated[formatted_date] = int(birth['births'])
    # print(births_abbreviated)

    # 4.
    total_births_by_year = {}
    for birth in births:
        year = birth['year']
        if year not in total_births_by_year:
            total_births_by_year[year] = 0
        total_births_by_year[year] += int(birth['births'])

    # 按值的升序排序TOTAL-BIRTHS-BY-YEAR的键/值对
    sorted_total_births_by_year = dict(sorted(total_births_by_year.items(), key=lambda item: item[1]))
    # print(sorted_total_births_by_year)

    # 5.
    births_by_year = {}
    for birth in births:
        year = birth['year']
        if year not in births_by_year:
            births_by_year[year] = []
        births_by_year[year].append(int(birth['births']))

    # Calculate average births per day for each year
    average_births_by_year = {}
    for year, births_list in births_by_year.items():
        print(len(births_list))
        average_births_by_year[year] = sum(births_list) / len(births_list)
        # Assuming each year has same number of days for simplicity

    # Find the year with the maximum average births
    max_average_births_map = list(sorted(average_births_by_year.items(), key=lambda item: item[1],reverse=True))[0]
    # 平均值最大的年份和对应的平均值
    max_average_births_year = max_average_births_map[0]
    max_average_births_value = max_average_births_map[1]



    # 6.
    csv_data = []
    for year, births_list in births_by_year.items():
        average_births = round(sum(births_list) / len(births_list),2)
        total_births = sum(births_list)

        csv_data.append([year, str(average_births), str(total_births)])

    # 写入CSV文件
    with open('output.csv', 'w', newline='') as csvfile:
        # 写入表头
        csvfile.write('year,average_births,total_births\n')

        # 写入数据行
        for row in csv_data:
            # 将数据转换为CSV格式的字符串
            csv_row = f"{row[0]},{row[1]},{row[2]}\n"  # 注意：这里假设average_births需要保留两位小数
            csvfile.write(csv_row)
